package cn.lanqiao.springboot.controller;

import cn.lanqiao.springboot.entity.User;
import cn.lanqiao.springboot.groupinterface.PhoneLogin;
import cn.lanqiao.springboot.groupinterface.UserLogin;
import cn.lanqiao.springboot.service.UserService;
import cn.lanqiao.springboot.util.Result;
import cn.lanqiao.springboot.vo.QueryUserVO;
import cn.lanqiao.springboot.vo.UserVO;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Api(tags = "用户管理功能")
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Value("${JWT.key}")
    String key;

    @Autowired
    RedisTemplate<String, Object> redisTemplate;

    @ApiOperation("用户登录功能实现")
    @PostMapping("/login")
    public Result login(@ApiParam("用户实体对象") @Validated({UserLogin.class}) @RequestBody User user) {
        UserVO retUser = userService.checkUser(user);
        //用户名是否正确
        if (retUser == null) {
            return Result.fail(601, "该用户不存在！");
        }
        //密码是否正确
        if (!BCrypt.checkpw(user.getPassword(), retUser.getPassword())) {
            return Result.fail(602, "输入密码错误！");
        }
        //签发JWT
        String token = JWT.create()
                .withClaim("userId", retUser.getUserId())//jwt中存用户id
                .withClaim("userName", retUser.getUserName())//jwt中存用户名
                .withClaim("roleId", retUser.getRoleId())//jwt中存用户id
                .withClaim("roleName", retUser.getRoleName())//jwt中存用户名
                .withExpiresAt(new Date(System.currentTimeMillis() + 1000 * 60 * 60))//设置失效时间一小时
                .sign(Algorithm.HMAC256(key));//设置秘钥。
        return Result.success(token);
    }

    @PostMapping("/insert")
    public Result insert(@RequestBody UserVO userVO) {
        String bcryptPassword = BCrypt.hashpw(userVO.getPassword(), BCrypt.gensalt());
        userVO.setPassword(bcryptPassword);
        userService.insert(userVO);
        return Result.success(userVO);
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody User user) {
        userService.delete(user.getUserId());
        return Result.success();
    }

    // /user/delete/1,2,3,4,5,6
    @DeleteMapping("/delete/{id}")
    public Result deleteAll(@PathVariable String id) {
        String[] ids = id.split(",");
        //userService.deleteAll(ids);
        return Result.success();
    }

    @PostMapping("/update")
    public Result update(@RequestBody UserVO userVO) {
        userVO.setPassword(BCrypt.hashpw(userVO.getPassword(), BCrypt.gensalt()));
        userService.update(userVO);
        return Result.success();
    }

    // B->S pageNum,pageSize
    // S->B List,total
    @PostMapping("/list")
    public Result list(@RequestBody QueryUserVO userVO) {
        PageHelper.startPage(userVO.getCurrentPage(), userVO.getPageSize());
        List<UserVO> userVOList = userService.getUserList(userVO);
        PageInfo<UserVO> pageInfo = new PageInfo<>(userVOList);
        return Result.success(pageInfo);
    }

    /**
     * 手机号登录功能
     */

    @ApiOperation("发送验证码")
    @PostMapping("/sendCode")
    public Result sendCode(@RequestBody @Validated({PhoneLogin.class}) User user) {
        //生成验证吗
        int code = new Random().nextInt(9000) + 1000;
        //存储redis
        String key = "phone:" + user.getPhone();
        redisTemplate.opsForValue().set(key, code);
        redisTemplate.expire(key, 30, TimeUnit.SECONDS);
        //发送验证码
        System.out.println("验证码为：" + code);
        return Result.success();
    }

    @ApiOperation("手机验证码登录")
    @PostMapping("/loginPhone/{code}")
    public Result loginPhone(@RequestBody @Validated({PhoneLogin.class}) User user, @PathVariable int code) {
        //redis是否存在该手机号
        Integer redisCode = (Integer) redisTemplate.opsForValue().get("phone:" + user.getPhone());
        if (redisCode == null) {
            return Result.fail(603, "该手机号好未发送验证码！");
        }
        //验证码是否正确
        if (redisCode != code) {
            return Result.fail(604, "验证码错误，请重新提交！");
        }
        //通过手机号获得用户信息
        //若是没有提示无该用户
        UserVO retUser = userService.getUserByPhone(user.getPhone());
        if (retUser == null) {
            return Result.fail(605, "该用户不存在！");
        }
        //有则生成有状态的token 1、生成128字符串 2、token存入redis
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("UserLogin:" + token, retUser);
        redisTemplate.expire("UserLogin:"  + token, 3, TimeUnit.MINUTES);
        return Result.success(token);
    }

    public Result register(User user){
        //password -> bcrypt()
        //userMapper.insert(user)
        //*** rabbitTemplate.convertAndSend("",email);
        return Result.success();
    }

}
